import { createRouter, createWebHistory } from 'vue-router'
import {useUserStore} from '@/stores'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 插件配置 修改颜色
NProgress.configure({
  showSpinner:false
})

/**
 * createRouter 路由实例  ==>  new VueRouter()
 * history模式(不带#)  (hash模式)(带#)  http://www.xxxx.com/#/xxxxxx
 */
const router = createRouter({
  // vite的配置  表示 根地址 '/'
  // 'http://www.xxx.com/xxxx/项目名称/user'
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path:'/login',
      component:()=> import('@/views/Login/index.vue')
    },
    {
      path: '/user/LikeMinded',
      component: () => import('@/views/User/LikeMindedPage.vue'),
      meta: { title: '嗯嗯大军' }
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        { path: '/home', 
          component: () => import('@/views/Home/index.vue'),
          // 元数据
          meta:{title:'首页'}
        },
        { path: '/article', component: () => import('@/views/Article/index.vue'),
          meta:{title:'小知识'} },
        { path: '/notify', component: () => import('@/views/Notify/index.vue'),
          meta:{title:'通知'} },
        { path: '/user', component: () => import('@/views/User/index.vue'),
          meta:{title:'个人中心'} }
      ]
    }
  ]
})

// 全局路由守卫

router.beforeEach((to)=>{
  NProgress.start()
  // user信息 store
  const store = useUserStore()
  // 不需要登陆的页面  白名单
  const  whiteList = ['/login','/register']
  
  // 没登陆 并且 不在白名单内 强制去登陆
  if(!store.user?.token && !whiteList.includes(to.path)) return '/login'
})

router.afterEach((to)=>{
  // 修改标题
  document.title = `${to.meta.title || '祝您健康' } -- 嗯嗯通畅`
  NProgress.done()
})


export default router
